/*
 * ========================================================
 * Copyright(c) 2014 杭州龙骞科技-版权所有
 * ========================================================
 * 本软件由杭州龙骞科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 * http://www.hzdracom.com/
 * ========================================================
 */
package com.shwread.android.qysw.activity;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.dao.UserDao;
import logic.util.NetworkUtil;
import logic.util.Util;

import org.geometerplus.android.util.QyreaderPerferencesUtil;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ciko.code.bean.UserBean;
import com.netease.nim.demo.NimCache;
import com.netease.nim.demo.config.preference.Preferences;
import com.netease.nim.demo.contact.cache.ContactDataCache;
import com.netease.nim.demo.contact.cache.TeamDataCache;
import com.netease.nim.demo.contact.cache.TeamMemberInfoCache;
import com.netease.nim.demo.contact.protocol.ContactHttpClient;
import com.netease.nim.demo.database.DatabaseManager;
import com.netease.nimlib.sdk.AbortableFuture;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.auth.AuthService;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.shwread.android.qysw10000204.R;
import com.shwread.android.ui.dialog.AccountLockedDialog;
import com.shwread.android.ui.dialog.BookTicketActivateDialog;
import com.shwread.android.ui.dialog.LoginHelpDialog;
import com.shwread.android.ui.dialog.NetworkDialog;
import com.shwread.android.ui.dialog.ServiceTimeOutDialog;
import com.shwread.httpsdk.constant.ResultCode;
import com.shwread.httpsdk.http.callback.ActionListener;
import com.shwread.httpsdk.http.face.CheckEcardAction;
import com.shwread.httpsdk.http.face.UserLoginAction;
import com.shwread.httpsdk.util.Base64;
import com.shwread.httpsdk.util.DESUtil;


public class LoginActivity
        extends
        BaseSimpleActivity
        implements
        OnClickListener,
        OnItemClickListener,
        ActionListener
{
	private static final int           LOGINCHANGEACCOUNTREFESH = 101;
	private static final int           NIMLOGINRESET            = 1221;
	private static final int           NIMLOGINREWAIT           = 1222;
	private static final int           NIMLOGINNORESPONSE       = 408;
	private AutoCompleteTextView       etUser                   = null;
	private EditText                   etPassword               = null;
	private CheckBox                   cbRememberPwd            = null;
	private Button                     btnForgetPwd             = null;
	private Button                     btnLogin                 = null;
	private RelativeLayout             rlayRememberPwd          = null;
	private ImageView                  ivChangeAccount, ivAccountClear, ivClearPwd;
	
	private Context                    mContext;
	private View                       accountLayout;
	
	private AbortableFuture<LoginInfo> loginRequest;
	
	private String                     account                  = "";
	private String                     pwd                      = "";
	private UserBean user                     = null;
	
	private List<UserBean>             users;
	private PopupWindow                moreAccountPup;
	private LoginChangeAccountAdapter  mAdapter;
	
	private Button                     btnBookTicketRecharge;

	private boolean                    nimLoginHasResponse      = false;//云信登录是否有响应
	
	@SuppressLint ("HandlerLeak")
	private Handler                    mhandler                 = new Handler()
	                                                            {
		                                                            
		                                                            @Override
		                                                            public void handleMessage(Message msg) {
			                                                            			                                                            switch (msg.what) {
			                                                            //																			case LOGINCHANGEACCOUNTREFESH:
			                                                            //																				initLoginUser();
			                                                            //																				break;
			                                                            //																			case DefaultConsts.GO_BOOKTICKET:
			                                                            //																				Intent intent = new Intent(LoginActivity.this, BookTicketActivity.class);
			                                                            //																				intent.putExtra(DefaultConsts.from_page, DefaultConsts.TAG_LOGIN);
			                                                            //																				startActivity(intent);
			                                                            //																				finish();
			                                                            //																				break;
			                                                            //																			case ResultCode.OK:
			                                                            //																				setEnable(true);
			                                                            //																				getSyncData();
			                                                            //																				toMainActivity();
			                                                            //																				break;
																																					case NIMLOGINRESET:
																																						System.err.println("NimLogin Reset");
																																						loginRequest.abort();
																																						NIMClient.getService(AuthService.class).logout();
																																						new Timer().schedule(new TimerTask() {
																																							@Override
																																							public void run() {
																																								loginRequest = NIMClient.getService(AuthService.class).login(new LoginInfo(nimAccount, nimPwd));
																																								loginRequest.setCallback(callback);
																																								mhandler.sendEmptyMessage(NIMLOGINREWAIT);
																																							}
																																						}, 3000);
																																						break;
																																					case NIMLOGINREWAIT:
																																						//如果重新请求依然无响应，则给出提示
																																						new Timer().schedule(new TimerTask() {
																																							@Override
																																							public void run() {
																																								if (!nimLoginHasResponse)
																																								{
																																									mhandler.sendEmptyMessage(NIMLOGINNORESPONSE);
																																								}
																																							}
																																						}, 3000);
																																						break;
																																					case NIMLOGINNORESPONSE:
																																						System.err.println("NimLogin No Response");
																																						loginRequest.abort();
																																						callback.onFailed(408);
																																						break;
			                                                            																		}
		                                                            }
		                                                            
	                                                            };
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.login_page);
		mContext = this;
		//		users = UserDao.getInstance(mContext).getAllUser();
		//		initView();
		//		setListener();
		//		initData();
		//		showHelp();
		//		
		//		initLoginUser();
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_SPACE) return true;
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		//		initData();
		//		initLoginUser();
		//		if (Const.isActivationError && Util.isNotEmpty(Const.tempCard) && Util.isNotEmpty(Const.tempCardPwd))
		//		{
		//			etUser.setText(Const.tempCard);
		//			etPassword.setText(Const.tempCardPwd);
		//			
		//			ivAccountClear.setVisibility(etUser.isFocused() ? View.VISIBLE : View.GONE);
		//			ivClearPwd.setVisibility(etPassword.isFocused() ? View.VISIBLE : View.GONE);
		//			etUser.setSelection(etUser.getText().length());
		//		}
	}
	
	void initData() {
		if (Util.isNotEmpty(Const.login_key)) Const.clear();
	}
	
	void initView() {
		etUser = (AutoCompleteTextView) super.findViewById(R.id.login_page_user_autv);
		etPassword = (EditText) findViewById(R.id.login_page_pwd_et);
		cbRememberPwd = (CheckBox) findViewById(R.id.login_page_remember_pwd_cbox);
		btnForgetPwd = (Button) findViewById(R.id.login_page_forget_pwd_btn);
		btnLogin = (Button) findViewById(R.id.login_page_enter_btn);
		rlayRememberPwd = (RelativeLayout) findViewById(R.id.login_page_remember_pwd_rlay);
		ivChangeAccount = (ImageView) findViewById(R.id.login_page_user_change_iv);
		btnBookTicketRecharge = (Button) findViewById(R.id.login_page_book_ticket_activate_btn);
		
		accountLayout = findViewById(R.id.login_page_user_rl);
		ivAccountClear = (ImageView) findViewById(R.id.login_page_user_clear_iv);
		ivClearPwd = (ImageView) findViewById(R.id.login_page_pwd_clear_iv);
	}
	
	void setListener() {
		btnLogin.setOnClickListener(this);
		btnForgetPwd.setOnClickListener(this);
		rlayRememberPwd.setOnClickListener(this);
		ivChangeAccount.setOnClickListener(this);
		btnBookTicketRecharge.setOnClickListener(this);
		ivAccountClear.setOnClickListener(this);
		ivClearPwd.setOnClickListener(this);
		etUser.setOnFocusChangeListener(new FocusChangeListener(etUser, ivAccountClear));
		etPassword.addTextChangedListener(new TextChangedListener(ivClearPwd));
		etPassword.setOnFocusChangeListener(new FocusChangeListener(etPassword, ivClearPwd));
		etUser.addTextChangedListener(new TextWatcher()
		{
			
			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
				
			}
			
			@Override
			public void afterTextChanged(Editable arg0) {
				if (Util.isEmpty(etUser.getText().toString()))
				{
					ivAccountClear.setVisibility(View.GONE);
					etPassword.setText("");
					ivChangeAccount.setVisibility(View.GONE);
				}
				else
				{
					ivAccountClear.setVisibility(View.VISIBLE);
				}
			}
		});
	}
	
	void initLoginUser() {
		user = UserDao.getInstance(mContext).getLastLoginUser();
		if (null == user)
		{
			etUser.setText("");
			etPassword.setText("");
			ivChangeAccount.setVisibility(View.GONE);
		}
		else
		{
			ivChangeAccount.setVisibility(View.VISIBLE);
			if (user.getIsKeepPwd() == 1)
			{
				cbRememberPwd.setChecked(true);
				etUser.setText(user.getAccount());
				etPassword.setText(Base64.decode(user.getPassword(), "utf-8"));
			}
			else
			{
				cbRememberPwd.setChecked(false);
				etUser.setText(user.getAccount());
				etPassword.setText("");
			}
			ivAccountClear.setVisibility(etUser.isFocused() ? View.VISIBLE : View.GONE);
			ivClearPwd.setVisibility(etPassword.isFocused() ? View.VISIBLE : View.GONE);
			etUser.setSelection(etUser.getText().length());
		}
	}
	
	@SuppressWarnings ("deprecation")
	void initDropPop(List<UserBean> users) {
		View view = LayoutInflater.from(this).inflate(R.layout.login_change_account_dialog, null);
		ListView changeListView = (ListView) view.findViewById(R.id.login_change_account_listview);
		changeListView.setOnItemClickListener(this);
		changeListView.setFocusable(true);
		changeListView.setFocusableInTouchMode(true);
		changeListView.setDivider(new ColorDrawable(Color.GRAY));
		changeListView.setCacheColorHint(Color.TRANSPARENT);
		changeListView.setDividerHeight(1);
		mAdapter = new LoginChangeAccountAdapter(mContext, users);
		changeListView.setAdapter(mAdapter);
		mAdapter.notifyDataSetChanged();
		moreAccountPup = new PopupWindow(view, accountLayout.getWidth(), LayoutParams.WRAP_CONTENT);
		moreAccountPup.setBackgroundDrawable(new BitmapDrawable());
		moreAccountPup.setFocusable(true);
		moreAccountPup.showAsDropDown(accountLayout, 0, 0);
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.login_page_enter_btn:
				clickLogin();
				break;
			case R.id.login_page_forget_pwd_btn:
				Intent forgetPwdIntent = new Intent(this, ForgetPwdActivity.class);
				forgetPwdIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(forgetPwdIntent);
				break;
			case R.id.login_page_remember_pwd_rlay:
				cbRememberPwd.setChecked(!cbRememberPwd.isChecked());
				if (user != null)
				{
					user.setIsKeepPwd(cbRememberPwd.isChecked() ? 1 : 0);
				}
				break;
			case R.id.login_page_user_change_iv:
				if (users != null && users.size() > 0)
				{
					initDropPop(users);
				}
				break;
			case R.id.login_page_book_ticket_activate_btn:
				Intent intent = new Intent(LoginActivity.this, BookTicketActivity.class);
				intent.putExtra(DefaultConsts.from_page, DefaultConsts.TAG_LOGIN);
				startActivity(intent);
				finish();
				break;
			case R.id.login_page_user_clear_iv:
				etUser.setText("");
				ivAccountClear.setVisibility(View.GONE);
				break;
			case R.id.login_page_pwd_clear_iv:
				etPassword.setText("");
				ivClearPwd.setVisibility(View.GONE);
				break;
		}
		
	}
	
	private void setEnable(boolean enabled) {
		etUser.setEnabled(enabled);
		etPassword.setEnabled(enabled);
		btnForgetPwd.setEnabled(enabled);
		btnLogin.setEnabled(enabled);
		cbRememberPwd.setEnabled(enabled);
		rlayRememberPwd.setEnabled(enabled);
		btnLogin.setText(enabled ? "登录" : "正在登录...");
	}
	
	void clickLogin() {
		if (NetworkUtil.isConnected(this))
		{
			checkLogin();
		}
		else
		{
			if (UserDao.getInstance(mContext).getLastLoginUser() != null)
			{
				if (QyreaderPerferencesUtil.getInstance(mContext, UserDao.getInstance(mContext).getLastLoginUser().getAccount()).getExistBookShelfPage())
				{
					new NetworkDialog(this).show();
				}
				else
				{
					Util.showToast(mContext, "网络未连接，请检查网络设置");
				}
			}
			else
			{
				Util.showToast(mContext, "网络未连接，请检查网络设置");
			}
		}
	}
	
	void checkLogin() {
		account = etUser.getText().toString();
		pwd = etPassword.getText().toString();
		
		if (Util.isEmpty(account))
		{
			Util.showToast(this, "请输入帐号");
		}
		else if (Util.isEmpty(pwd))
		{
			Util.showToast(this, "请输入密码");
		}
		else
		{
			setEnable(false);
			if (account.startsWith("1"))
			{
				if (Util.isMobile(account))
				{
					onLogout();
					if (account.startsWith("15") || account.startsWith("14"))
					{
						//电子券激活
						new CheckEcardAction(mContext, "", account, pwd, "0", new MActionListener()).start();
					}
					else
					{
						//IM账号登出
						//						NIMClient.getService(AuthService.class).logout();
						new UserLoginAction(this, account, pwd, this).start();
					}
				}
				else
				{
					Util.showToast(this, "请输入正确的帐号");
					setEnable(true);
				}
			}
			else
			{
				//电子券激活
				new CheckEcardAction(mContext, "", account, pwd, "0", new MActionListener()).start();
			}
		}
	}
	
	private void onLogout() {
		if (!TextUtils.isEmpty(NimCache.getAccount()))
		{
			TeamMemberInfoCache.destroy();
			TeamDataCache.getInstance().clearAll();
			ContactDataCache.getInstance().clearAll();
			NimCache.clear();
			Preferences.saveUserToken("");
			DatabaseManager.getInstance().close();
			ContactDataCache.getInstance().clearBuddyCache();
			TeamDataCache.getInstance().clearTeamCache();
			ContactHttpClient.getInstance().resetToken();
		}
		NIMClient.getService(AuthService.class).logout();
	}
	
	private BookTicketActivateDialog dialog;
	
	private void showDialog(String msg) {
		if (dialog != null)
		{
			if (dialog.isShowing()) dialog.dismiss();
			dialog = null;
		}
		dialog = new BookTicketActivateDialog(mContext, false, msg, null);
		dialog.show();
	}
	
	/** 电子券激活完成的操作 */
	private void activationFinish() {
		Intent intent = new Intent(mContext, LoginAfterBookTicketActivateActivity.class);
		String _num = "", _pwd = "";
		try
		{
			_num = DESUtil.encrypt(account);
			_pwd = DESUtil.encrypt(pwd);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
		intent.putExtra(DefaultConsts.FROM_TYPE, DefaultConsts.TAG_LOGIN);
		intent.putExtra(DefaultConsts.CURR_CARD, _num);
		intent.putExtra(DefaultConsts.CURR_PASSWORD, _pwd);
		startActivity(intent);
		finish();
	}
	
	class MActionListener
	        implements
	        ActionListener
	{
		
		@Override
		public void OK(Object obj) {
			mhandler.post(new Runnable()
			{
				@Override
				public void run() {
					setEnable(true);
					Const.tempCard = etUser.getText().toString();
					Const.tempCardPwd = etPassword.getText().toString();
					activationFinish();
				}
			});
		}
		
		@Override
		public void ERROR(final int code, final String msg) {
			mhandler.post(new Runnable()
			{
				@Override
				public void run() {
					if (account.startsWith("15"))
					{
						new UserLoginAction(mContext, account, pwd, LoginActivity.this).start();
					}
					else
					{
						setEnable(true);
						if (code == 2100)
						{//电子券信息错误,这个也需要显示dialog,待测试
							showDialog(msg);
						}
						else
						{
							Util.showToast(mContext, msg);
						}
					}
				}
			});
		}
		
		@Override
		public void HTTPERROR(int statusCode) {
			mhandler.post(new Runnable()
			{
				@Override
				public void run() {
					setEnable(true);
					Util.showToast(mContext, "请求超时，请重试！");
				}
			});
		}
	}
	
	void toMainActivity() {
		Intent intent = new Intent(LoginActivity.this, MainActivity.class);
		intent.setAction(MainActivity.TO_ENTERPRISE_ACTION);
		startActivity(intent);
		finish();
	}
	
	@Override
	public void OK(Object obj) {
		logic.bean.LoginInfo info = (logic.bean.LoginInfo) obj;
		Const.UserRole = info.getUserRole();
		Const.UserAccId = info.getAccId();
		Const.UserStaffId = info.getStaffId();
		UserBean user = UserDao.getInstance(mContext).getUser(account);
		long loginTime = System.currentTimeMillis();
		
		if (null == user)
		{
			user = new UserBean(account, Base64.encode(pwd, "utf-8"), info.getKey(), loginTime, cbRememberPwd.isChecked() ? 1 : 0, info.getAccId(), info.getToken(), info.getStaffId());
		}
		else
		{
			user.setPassword(Base64.encode(pwd, "utf-8"));
			user.setLoginTime(loginTime);
			user.setKey(info.getKey());
			user.setStaffId(info.getStaffId());
			user.setIsKeepPwd(cbRememberPwd.isChecked() ? 1 : 0);
		}
		UserDao.getInstance(this).addUser(user);
		
		//登录云信平台
		doNimlogin(info.getAccId(), info.getToken());
	}

	private RequestCallback callback;
	private String nimAccount;
	private String nimPwd;
	
	/** 云信登录接口 */
	@SuppressWarnings ("unchecked")
	void doNimlogin(final String nimAccount, final String nimPwd) {
		System.out.println("doNimLogin");
		nimLoginHasResponse = false;
		this.nimAccount = nimAccount;
		this.nimPwd = nimPwd;
		loginRequest = NIMClient.getService(AuthService.class).login(new LoginInfo(nimAccount, nimPwd));
		callback = new RequestCallback<LoginInfo>()
		{
			@Override
			public void onSuccess(final LoginInfo param) {
				nimLoginHasResponse = true;
				NimCache.setAccount(account);
				saveLoginInfo(account, nimPwd);
				mhandler.sendEmptyMessage(ResultCode.OK);
				//NIMClient.getService(AuthService.class).login(param);
				DatabaseManager.getInstance().open(LoginActivity.this); // open db
			}

			@Override
			public void onFailed(final int code) {
				setEnable(true);
				nimLoginHasResponse = true;
				if (code == 302 || code == 404)
				{
					Toast.makeText(LoginActivity.this, "帐号或密码错误", Toast.LENGTH_SHORT).show();
				}
				else if (code == 408)
				{
					Toast.makeText(LoginActivity.this, "请求超时", Toast.LENGTH_SHORT).show();
				}
				else
				{
					Toast.makeText(LoginActivity.this, "login error: " + code, Toast.LENGTH_SHORT).show();
				}
			}

			@Override
			public void onException(final Throwable exception) {
				setEnable(true);
				nimLoginHasResponse = true;
			}
		};
		loginRequest.setCallback(callback);
		//云信登录可能会出现一直卡死无响应的情况
		//如果3秒后无响应，则取消请求并重新请求
		new Timer().schedule(new TimerTask() {
			@Override
			public void run() {
				if (!nimLoginHasResponse)
				{
					mhandler.sendEmptyMessage(NIMLOGINRESET);
				}
			}
		}, 3000);
	}
	
	@Override
	public void ERROR(final int resultCode, final String message) {
		mhandler.post(new Runnable()
		{
			@Override
			public void run() {
				setEnable(true);
				if (resultCode == ResultCode.E_9997)
				{
					AccountLockedDialog accountLockedDialog = new AccountLockedDialog(mContext);
					accountLockedDialog.show();
				}
				else if (resultCode == ResultCode.E_1101)
				{
					ServiceTimeOutDialog serviceTimeOutDialog = new ServiceTimeOutDialog(LoginActivity.this);
					serviceTimeOutDialog.show();
				}
				else
				{
					Util.showToast(mContext, message);
					//					Util.showToast(mContext, "帐号或密码错误");
				}
			}
		});
	}
	
	@Override
	public void HTTPERROR(int statusCode) {
		mhandler.post(new Runnable()
		{
			
			@Override
			public void run() {
				setEnable(true);
				Util.showToast(mContext, "登录失败，请稍候再试");
			}
		});
	}
	
	class LoginChangeAccountAdapter
	        extends
	        BaseAdapter
	{
		
		public List<UserBean> params;
		Context               mContext;
		
		public LoginChangeAccountAdapter(Context ct, List<UserBean> params) {
			mContext = ct;
			this.params = params;
		}
		
		@Override
		public int getCount() {
			return params == null ? 0 : params.size();
		}
		
		@Override
		public UserBean getItem(int position) {
			return params == null ? null : params.get(position);
		}
		
		@Override
		public long getItemId(int position) {
			return position;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			DeviceViewHolder viewHolder;
			if (convertView == null)
			{
				viewHolder = new DeviceViewHolder();
				convertView = LayoutInflater.from(mContext).inflate(R.layout.login_change_account_item, null);
				viewHolder.name = (TextView) convertView.findViewById(R.id.login_change_account_tv);
				viewHolder.delete = (ImageView) convertView.findViewById(R.id.login_change_account_delete_tv);
				convertView.setTag(viewHolder);
			}
			else
			{
				viewHolder = (DeviceViewHolder) convertView.getTag();
			}
			final UserBean itemBean = getItem(position);
			viewHolder.name.setText(itemBean.getAccount());
			viewHolder.name.setTag(itemBean);
			viewHolder.delete.setOnClickListener(new OnClickListener()
			{
				
				@Override
				public void onClick(View v) {
					etUser.setText("");
					etPassword.setText("");
					moreAccountPup.dismiss();
					UserDao.getInstance(mContext).deleteUser(itemBean.getAccount());
					users = UserDao.getInstance(mContext).getAllUser();
					mAdapter.notifyDataSetChanged();
					mhandler.sendEmptyMessage(LOGINCHANGEACCOUNTREFESH);
				}
			});
			return convertView;
		}
		
		class DeviceViewHolder
		{
			public TextView  name;
			public ImageView delete;
		}
		
	}
	
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		UserBean user = mAdapter.getItem(position);
		if (user != null)
		{
			moreAccountPup.dismiss();
			if (user.getIsKeepPwd() == 1)
			{
				cbRememberPwd.setChecked(true);
				etUser.setText(user.getAccount());
				etPassword.setText(Base64.decode(user.getPassword(), "utf-8"));
			}
			else
			{
				cbRememberPwd.setChecked(false);
				etUser.setText(user.getAccount());
				etPassword.setText("");
			}
			ivAccountClear.setVisibility(etUser.isFocused() ? View.VISIBLE : View.GONE);
			ivClearPwd.setVisibility(etPassword.isFocused() ? View.VISIBLE : View.GONE);
			if (etUser.isFocused())
			{
				etUser.setSelection(etUser.getText().length());
			}
			else if (etPassword.isFocused())
			{
				etPassword.setSelection(etPassword.getText().length());
			}
		}
	}
	
	public Handler getUIHandler() {
		return mhandler;
	}
	
	private class TextChangedListener
	        implements
	        TextWatcher
	{
		View view;
		
		public TextChangedListener(View view) {
			this.view = view;
		}
		
		@Override
		public void afterTextChanged(Editable arg0) {
		}
		
		@Override
		public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
		}
		
		@Override
		public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
			view.setVisibility(Util.isEmpty(s.toString()) ? View.GONE : View.VISIBLE);
		}
	}
	
	private class FocusChangeListener
	        implements
	        OnFocusChangeListener
	{
		View     view;
		EditText et;
		
		public FocusChangeListener(EditText et, View view) {
			this.view = view;
			this.et = et;
		}
		
		@Override
		public void onFocusChange(View arg0, boolean arg1) {
			boolean value = arg1 && Util.isNotEmpty(et.getText().toString().trim());
			view.setVisibility(value ? View.VISIBLE : View.GONE);
		}
	}
	
	@SuppressWarnings ("unused")
	private void showHelp() {
		QyreaderPerferencesUtil util = QyreaderPerferencesUtil.getInstance(this, DefaultConsts.FIRST_TAG);
		boolean showHelp = util.getShowLoginHelp();
		if (showHelp)
		{
			new LoginHelpDialog(this).show();
			util.setShowLoginHelp(false);
		}
	}
	
	private void saveLoginInfo(final String account, final String password) {
		Preferences.saveUserAccount(account);
		Preferences.saveUserToken(password);
	}
}
